var tz1989_uploader=function (opt) {
    var scope = this;
    var params = {
        id: "",//file控件的id
        url: "",//上传的url
        data: {},//上传的数据
        width: 200,//上传按钮的宽度
        height: 30,//上传按钮的高度
        value: "",//控件值的值
        icon: "",//上传按钮的图标
        text: "选择文件",//上传按钮的文本
        autoUpload: false,//是否自动上传,默认为false
        multiple: false,//是否允许多文件上传，默认为false
        accept:"",//允许上传的文件类型,默认为空,如：.jpg,.png,.gif
        css: {},//上传按钮的样式,默认为空,如：{ "color": "red" }
        cssClass: "",//上传按钮的cssClass
        //选择文件事件
        selecting: function (src, files, index) {

        },
        //上传中事件
        uploading: function (data, count) {
        },
        //上传成功事件
        success: function (data, file, index) {

        },
        //上传完成事件
        // 1：成功  0：失败  2：未完全上传完毕
        completed: function (code) {

        },
        //移除文件事件
        remove: function (index) {

        },
        //错误事件
        error: function (ex) {

        }
    };

    var global = {
        sender: null,
        btnupload: null,
        fileindex: 0,
        filesarray: null,
        succ_count: 0,
        unsucc_count: 0
    };

    var init = function () {
        //合并传入的参数和默认参数
        params = $.extend({}, params, opt);
        //上传的文件集合
        global.filesarray = new Array();
        //上传文件的索引
        global.fileindex = 0;
        //file控件
        global.sender = $("#" + params.id);
        //允许多文件上传
        if (params.multiple) {
            global.sender.prop("multiple", "multiple");
        }
        //隐藏上传控件
        global.sender.hide();
        //选择按钮
        if (params.icon != undefined && params.icon != "" && params.icon.length > 0) {
            global.btnupload = $("<a><img src='" + params.icon + "' width='" + params.width + "' height='" + params.height + "' /></a>");
        }
        else {
            global.btnupload = $("<a>" + params.text + "</a>");
        }

        //设置上传按钮的宽度和高度
        global.btnupload.css({ "display": "inline-block", "cursor": "pointer" });
        if (params.width != 0) {
            global.btnupload.css({ "width": params.width });
        }
        if (params.height != 0) {
            global.btnupload.css({ "height": params.height });
        }
        //设置上传按钮的cssClass
        if (params.cssClass != "") {
            global.btnupload.addClass(params.cssClass);
        }
        //设置上传按钮的style
        global.btnupload.css(params.css);
        //插入上传按钮
        global.sender.before(global.btnupload);
        global.sender.css({ "display": "none" });
        //上传按钮触发file.change事件
        global.btnupload.click(function () {
            global.sender.click();
        });

        //选择文件
        global.sender.change(function () {
            var file_c = this;
            //选择自动上传
            if (window.FileReader) { // html5方案
                for (var i = 0; i < file_c.files.length; i++) {
                    var acceptOk = checkAccept(file_c.files[i]);
                    if (acceptOk == false) {
                        scope.error({ message: "文件类型受限，请选择" + params.accept + "等类型文件" });
                        return;
                    }
                    global.fileindex++;
                    //存储上传的文件
                    global.filesarray.push({ index: global.fileindex, file: file_c.files[i] });
                    readFileAsURL(file_c.files[i], global.fileindex);

                }
                //选择自动上传
                if (params.autoUpload) {
                    scope.upload();
                }
            } else { // 降级处理

            }
            file_c.value = '';
        });


    };

    var checkAccept = function (file) {
        if (params.accept == undefined || params.accept == null || params.accept == "") {
            return true;
        }
        var acceptArray = params.accept.split(",");
        var fileName = file.name;
        var ext = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
        var isok = false;
        for (var i = 0; i < acceptArray.length; i++) {
            if (ext == acceptArray[i].toLowerCase()) {
                isok = true;
                break;
            }
        }
        return isok;
    }

    //读取本地文件
    var readFileAsURL = function (file, index) {
        var fr = new FileReader();
        fr.readAsDataURL(file);
        fr.onload = function (e) {
            var src = e.target.result;
            //触发选择事件
            if (params.selecting != undefined) {
                params.selecting(src, file, index);
            }
        }
    };

    //上传
    var uploadfile = function (file, index) {
        //params.data.file = file;
        //params.data.filename = filename;
        var formData = new FormData();
        formData.append(params.id, file);
        for (var datakey in params.data) {
            formData.append(datakey, params.data[datakey]);
        }
        $.ajax({
            url: params.url,
            type: "POST",
            data: formData,
            /**
            *必须false才会自动加上正确的Content-Type
            */
            contentType: false,
            /**
            * 必须false才会避开jQuery对 formdata 的默认处理
            * XMLHttpRequest会对 formdata 进行正确的处理
            */
            processData: false,
            success: function (data) {
                //上传成功
                if (params.success != undefined) {
                    params.succ_count++;
                    scope.removefile(index);
                    params.success(data, file, index);
                }
                else {
                    params.unsucc_count++;
                }
            },
            error: function (e) {
                params.unsucc_count++;
            }
        });
    };

    //上传文件
    scope.upload = function () {
        params.succ_count = 0;
        params.unsucc_count = 0;
        if (global.filesarray.length > 0) {
            var checkcompletehandler = null;
            var count = global.filesarray.length;
            if (params.uploading != undefined) {

                params.uploading({ message: "正在上传" }, global.filesarray.length);
            }
            //存储上传的文件
            var files = global.filesarray;
            for (var i = 0; i < files.length; i++) {
                uploadfile(files[i].file, files[i].index);
            }
            checkcompletehandler = setInterval(function () {
                clearInterval(checkcompletehandler);
                checkcomplete();
            }, 300);
            var checkcomplete = function () {

                if (global.filesarray.length == 0
                    || (params.succ_count + params.unsucc_count == count)) {
                    if (global.filesarray.length == 0) {
                        params.completed(1);
                    }
                    else if (global.filesarray.length == count) {
                        params.completed(0);
                    }
                    else {
                        params.completed(2);
                    }
                }
                else {
                    checkcompletehandler = setInterval(function () {
                        clearInterval(checkcompletehandler);
                        checkcomplete();
                    }, 300);
                }
            }
        }

        else {
            if (params.uploading != undefined) {
                params.uploading({
                    message: "没有选择任何文件"
                }, global.filesarray.length);
            }
        }
    };

    //移除文件
    scope.remove = function (index) {
        scope.removefile(index);
        if (params.remove != undefined) {
            params.remove(index);
        }
    };

    scope.removefile = function (index) {
        //存储上传的文件
        var files = global.filesarray;
        var newfiles = new Array();
        for (var i = 0; i < files.length; i++) {
            if (files[i].index == index) {
                continue;
            }
            newfiles.push(files[i]);
        }
        global.filesarray = newfiles;
    };

    //清除所有
    scope.clear = function () {
        global.filesarray = new Array();
    };

    //选择文件事件
    scope.change = function () {
        global.btnupload.click();
    };

    scope.error = function (ex) {
        if (params.error != undefined) {
            params.error(ex);
        } else {
            alert(ex.message);
        }
    }

    init();
    scope.filelength = function () { return global.filesarray.length; };
    return scope;
}